package com.oraro.paygatewaybiz.module.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oraro.paygatewaybiz.constant.Constants;
import com.oraro.paygatewaybiz.module.dao.MchDao;
import com.oraro.paygatewaybiz.module.entity.MchEntity;
import com.oraro.paygatewaybiz.module.service.MchService;
import com.oraro.paygatewaybiz.utils.Query;
import com.oraro.paygatewaybiz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;



@Service("mchService")
public class MchServiceImpl extends ServiceImpl<MchDao, MchEntity> implements MchService {

    @Autowired
    private RedisUtil redisUtil;

    private static final String key = Constants.CacheType.MCHCACHE.getType();

    @Override
    public IPage<MchEntity> queryPage(Map<String, Object> params) {
        String mchInfo = (String)params.get("mchInfo");
        IPage<MchEntity> page = this.page(
                new Query<MchEntity>(params).getPage(),
                new QueryWrapper<MchEntity>().like(mchInfo != null, "mch_info", mchInfo)
        );

        return page;
    }

    @Override
    public MchEntity selectByMchId(Long mchId) {
        String hKey = mchId.toString();
        MchEntity mchEntity;
        if (redisUtil.hHasKey(key, hKey)) {
            mchEntity = redisUtil.hget(key, hKey, MchEntity.class);
        } else {
            mchEntity = baseMapper.selectByMchId(mchId);
            if (mchEntity != null) {
                redisUtil.hset(key, hKey, mchEntity);
            }
        }
        return mchEntity;
    }

    @Override
    public List<MchEntity> queryList(Map<String, Object> params) {
        return this.list(new QueryWrapper<>());
    }

    @Override
    public void update(MchEntity mchEntity) {
        changeCache(mchEntity.getMchId());
        this.updateById(mchEntity);
    }

    @Override
    public boolean delete(Long[] mchIds) {
        Arrays.asList(mchIds).forEach((mchId -> changeCache(mchId)));
        return this.removeByIds(Arrays.asList(mchIds));
    }

    @Async
    public void changeCache(Long mchId){
        redisUtil.hdel(key,mchId);
    }

}
